/*
 * TcpMediaCasterServer.cpp
 *
 *  Created on: 2016-6-20
 *      Author: terry
 */

#include "TcpMediaCasterServer.h"
#include "TcpMediaCasterConnection.h"


namespace av
{


TcpMediaCasterServer::TcpMediaCasterServer()
{
}

TcpMediaCasterServer::~TcpMediaCasterServer()
{
}

bool TcpMediaCasterServer::start(const char* ip, int port, const std::string& params)
{
	return TcpServer::start(ip, port);
}

bool TcpMediaCasterServer::isStarted()
{
	return TcpServer::isStarted();
}

void TcpMediaCasterServer::stop()
{
	TcpServer::stop();
}

void TcpMediaCasterServer::close(const char* name)
{

}

void TcpMediaCasterServer::closeAll()
{
	TcpServer::closeAll();
}

TcpConnectionPtr TcpMediaCasterServer::create(evutil_socket_t fd)
{
    struct sockaddr_in addr;
    int len = sizeof(addr);
    getpeername(fd, (sockaddr*)&addr, &len);

    MediaCasterEvent event;
    event.type = kCaster_create;
    event.ip = inet_ntoa(addr.sin_addr);
    event.port = ntohs(addr.sin_port);
    fireEvent(event, kTcpCaster);


	TcpMediaCasterConnection* conn = new TcpMediaCasterConnection();
	return TcpConnectionPtr(conn);
}

void TcpMediaCasterServer::onAcquireStream(const std::string& name, TcpConnectionPtr& conn)
{
    evutil_socket_t fd = conn->getSocket();
    struct sockaddr_in addr;
    int len = sizeof(addr);
    getpeername(fd, (sockaddr*)&addr, &len);

    MediaCasterEvent event;
    event.type = kCaster_acquire;
    event.ip = inet_ntoa(addr.sin_addr);
    event.port = ntohs(addr.sin_port);
    event.streamName = name;
    fireEvent(event, kTcpCaster);
}

void TcpMediaCasterServer::onClose(TcpConnectionPtr& conn)
{
    evutil_socket_t fd = conn->getSocket();
    struct sockaddr_in addr;
    int len = sizeof(addr);
    getpeername(fd, (sockaddr*)&addr, &len);

    MediaCasterEvent event;
    event.type = kCaster_destroy;
    event.ip = inet_ntoa(addr.sin_addr);
    event.port = ntohs(addr.sin_port);

    TcpMediaCasterConnection* casterConn = (TcpMediaCasterConnection*)conn.get();
    event.streamName = casterConn->getStreamName();

    fireEvent(event, kTcpCaster);
}



} /* namespace av */
